{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "t09eeeR5prIJ"
   },
   "source": [
    "##### Copyright 2020 The TensorFlow Authors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "cellView": "form",
    "id": "GCCk8_dHpuNf"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ovpZyIhNIgoq"
   },
   "source": [
    "# Text generation with an RNN"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hcD2nPQvPOFM"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/text/text_generation\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BwpJ5IffzRG6"
   },
   "source": [
    "This tutorial demonstrates how to generate text using a character-based RNN. We will work with a dataset of Shakespeare's writing from Andrej Karpathy's [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Given a sequence of characters from this data (\"Shakespear\"), train a model to predict the next character in the sequence (\"e\"). Longer sequences of text can be generated by calling the model repeatedly.\n",
    "\n",
    "Note: Enable GPU acceleration to execute this notebook faster. In Colab: *Runtime > Change runtime type > Hardware accelerator > GPU*. If running locally make sure TensorFlow version >= 2.4.\n",
    "\n",
    "This tutorial includes runnable code implemented using [tf.experimental.numpy](https://www.tensorflow.org/api_docs/python/tf/experimental/numpy). The following is sample output when the model in this tutorial trained for 30 epochs, and started with the string \"Q\":\n",
    "\n",
    "<pre>\n",
    "QUEENE:\n",
    "I had thought thou hadst a Roman; for the oracle,\n",
    "Thus by All bids the man against the word,\n",
    "Which are so weak of care, by old care done;\n",
    "Your children were in your holy love,\n",
    "And the precipitation through the bleeding throne.\n",
    "\n",
    "BISHOP OF ELY:\n",
    "Marry, and will, my lord, to weep in such a one were prettiest;\n",
    "Yet now I was adopted heir\n",
    "Of the world's lamentable day,\n",
    "To watch the next way with his father with his face?\n",
    "\n",
    "ESCALUS:\n",
    "The cause why then we are all resolved more sons.\n",
    "\n",
    "VOLUMNIA:\n",
    "O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,\n",
    "And love and pale as any will to that word.\n",
    "\n",
    "QUEEN ELIZABETH:\n",
    "But how long have I heard the soul for this world,\n",
    "And show his hands of life be proved to stand.\n",
    "\n",
    "PETRUCHIO:\n",
    "I say he look'd on, if I must be content\n",
    "To stay him from the fatal of our country's bliss.\n",
    "His lordship pluck'd from this sentence then for prey,\n",
    "And then let us twain, being the moon,\n",
    "were she such a case as fills m\n",
    "</pre>\n",
    "\n",
    "While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:\n",
    "\n",
    "* The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.\n",
    "\n",
    "* The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.\n",
    "\n",
    "* As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "srXC6pLGLwS6"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WGyKZj3bzf9p"
   },
   "source": [
    "### Import TensorFlow and other libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "yG_n40gFzf9s"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import tensorflow.experimental.numpy as tnp\n",
    "\n",
    "import numpy as np\n",
    "import os\n",
    "import time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EHDoRoc5PKWz"
   },
   "source": [
    "### Download the Shakespeare dataset\n",
    "\n",
    "Change the following line to run this code on your own data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "pD_55cOxLkAb"
   },
   "outputs": [],
   "source": [
    "path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UHjdCjDuSvX_"
   },
   "source": [
    "### Read the data\n",
    "\n",
    "First, look in the text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "aavnuByVymwK"
   },
   "outputs": [],
   "source": [
    "# Read, then decode for py2 compat.\n",
    "text = open(path_to_file, 'rb').read().decode(encoding='utf-8')\n",
    "# length of text is the number of characters in it\n",
    "print ('Length of text: {} characters'.format(len(text)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "Duhg9NrUymwO"
   },
   "outputs": [],
   "source": [
    "# Take a look at the first 250 characters in text\n",
    "print(text[:250])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "IlCgQBRVymwR"
   },
   "outputs": [],
   "source": [
    "# The unique characters in the file\n",
    "vocab = sorted(set(text))\n",
    "print ('{} unique characters'.format(len(vocab)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rNnrKn_lL-IJ"
   },
   "source": [
    "## Process the text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LFjSVAlWzf-N"
   },
   "source": [
    "### Vectorize the text\n",
    "\n",
    "Before training, we need to map strings to a numerical representation. Create two lookup tables: one mapping characters to numbers, and another for numbers to characters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "IalZLbvOzf-F"
   },
   "outputs": [],
   "source": [
    "# Creating a mapping from unique characters to indices\n",
    "char2idx = {u:i for i, u in enumerate(vocab)}\n",
    "idx2char = np.array(vocab)\n",
    "\n",
    "text_as_int = np.array([char2idx[c] for c in text])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bbmsf23Bymwe"
   },
   "source": [
    "### The prediction task"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "wssHQ1oGymwe"
   },
   "source": [
    "Given a character, or a sequence of characters, what is the most probable next character? This is the task we're training the model to perform. The input to the model will be a sequence of characters, and we train the model to predict the output—the following character at each time step.\n",
    "\n",
    "Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hgsVvVxnymwf"
   },
   "source": [
    "### Create training examples and targets\n",
    "\n",
    "Next divide the text into example sequences. Each input sequence will contain `seq_length` characters from the text.\n",
    "\n",
    "For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.\n",
    "\n",
    "So break the text into chunks of `seq_length+1`. For example, say `seq_length` is 4 and our text is \"Hello\". The input sequence would be \"Hell\", and the target sequence \"ello\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "0UHJDA39zf-O"
   },
   "outputs": [],
   "source": [
    "# The maximum length sentence we want for a single input in characters\n",
    "seq_length = 100\n",
    "examples_per_epoch = len(text)//(seq_length+1)\n",
    "\n",
    "# Create training examples / targets\n",
    "char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)\n",
    "\n",
    "for i in char_dataset.take(5):\n",
    "  print(idx2char[i.numpy()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "l4hkDU3i7ozi"
   },
   "outputs": [],
   "source": [
    "sequences = char_dataset.batch(seq_length+1, drop_remainder=True)\n",
    "\n",
    "for item in sequences.take(5):\n",
    "  print(repr(''.join(idx2char[item.numpy()])))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "9NGu-FkO_kYU"
   },
   "outputs": [],
   "source": [
    "def split_input_target(chunk):\n",
    "    input_text = chunk[:-1]\n",
    "    target_text = chunk[1:]\n",
    "    return input_text, target_text\n",
    "\n",
    "dataset = sequences.map(split_input_target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "GNbw-iR0ymwj"
   },
   "outputs": [],
   "source": [
    "for input_example, target_example in  dataset.take(1):\n",
    "  print ('Input data: ', repr(''.join(idx2char[input_example.numpy()])))\n",
    "  print ('Target data:', repr(''.join(idx2char[target_example.numpy()])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_33OHL3b84i0"
   },
   "source": [
    "Each index of these vectors are processed as one time step. For the input at time step 0, the model receives the index for \"F\" and tries to predict the index for \"i\" as the next character. At the next timestep, it does the same thing but the `RNN` considers the previous step context in addition to the current input character."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "0eBu9WZG84i0"
   },
   "outputs": [],
   "source": [
    "for i, (input_idx, target_idx) in enumerate(zip(input_example[:5], target_example[:5])):\n",
    "    print(\"Step {:4d}\".format(i))\n",
    "    print(\"  input: {} ({:s})\".format(input_idx, repr(idx2char[input_idx])))\n",
    "    print(\"  expected output: {} ({:s})\".format(target_idx, repr(idx2char[target_idx])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "MJdfPmdqzf-R"
   },
   "source": [
    "### Create training batches\n",
    "\n",
    "We used `tf.data` to split the text into manageable sequences. But before feeding this data into the model, we need to shuffle the data and pack it into batches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "p2pGotuNzf-S"
   },
   "outputs": [],
   "source": [
    "# Batch size\n",
    "BATCH_SIZE = 64\n",
    "\n",
    "# Buffer size to shuffle the dataset\n",
    "# (TF data is designed to work with possibly infinite sequences,\n",
    "# so it doesn't attempt to shuffle the entire sequence in memory. Instead,\n",
    "# it maintains a buffer in which it shuffles elements).\n",
    "BUFFER_SIZE = 10000\n",
    "\n",
    "dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)\n",
    "\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "r6oUuElIMgVx"
   },
   "source": [
    "## Build The Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oKesgVJRY9g4"
   },
   "source": [
    "We manually implement the model from scratch, using `tf.numpy` and some low-level TF ops. A `Model` object has three layers: `Embedding`, `GRU` and `Dense`. `Embedding` and `Dense` are little more than just wrappers around `tnp.take` and `tnp.dot`, but we can use them to familiarize ourself with the structure of a layer. Each layer has two essential methods: `build` and `__call__`. `build` creates and initializes the layer's weights and state, which are things that change during the training process. `__call__` is the forward function that calculates outputs given inputs, using the layer's weights and state internally."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9dm_WoL29UmO"
   },
   "source": [
    "Our model (more precisely the `GRU` layer) is stateful, because each call of `__call__` will change its internal state, affecting the next call. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "zHT8cLh7EAsg"
   },
   "outputs": [],
   "source": [
    "# Length of the vocabulary in chars\n",
    "vocab_size = len(vocab)\n",
    "\n",
    "# The embedding dimension\n",
    "embedding_dim = 256\n",
    "\n",
    "# Number of RNN units\n",
    "rnn_units = 1024"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "dGrbGm-oGnqB"
   },
   "outputs": [],
   "source": [
    "class Embedding:\n",
    "\n",
    "  def __init__(self, vocab_size, embedding_dim):\n",
    "    self._vocab_size = vocab_size\n",
    "    self._embedding_dim = embedding_dim\n",
    "    self._built = False\n",
    "\n",
    "  def __call__(self, inputs):\n",
    "    if not self._built:\n",
    "      self.build(inputs)\n",
    "    return tnp.take(self.weights, inputs, axis=0)\n",
    "\n",
    "  def build(self, inputs):\n",
    "    del inputs\n",
    "    self.weights = tf.Variable(tnp.random.randn(\n",
    "        self._vocab_size, self._embedding_dim).astype(np.float32))\n",
    "    self._built = True\n",
    "\n",
    "\n",
    "class GRUCell:\n",
    "  \"\"\"Builds a traditional GRU cell with dense internal transformations.\n",
    "\n",
    "  Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555\n",
    "  \"\"\"\n",
    "\n",
    "  def __init__(self, n_units, forget_bias=0.0):\n",
    "    self._n_units = n_units\n",
    "    self._forget_bias = forget_bias\n",
    "    self._built = False\n",
    "\n",
    "  def __call__(self, inputs):\n",
    "    if not self._built:\n",
    "      self.build(inputs)\n",
    "    x, gru_state = inputs\n",
    "    # Dense layer on the concatenation of x and h.\n",
    "    y = tnp.dot(tnp.concatenate([x, gru_state], axis=-1), self.w1) + self.b1\n",
    "    # Update and reset gates.\n",
    "    u, r = tnp.split(tf.sigmoid(y), 2, axis=-1)\n",
    "    # Candidate.\n",
    "    c = tnp.dot(tnp.concatenate([x, r * gru_state], axis=-1), self.w2) + self.b2\n",
    "    new_gru_state = u * gru_state + (1 - u) * tnp.tanh(c)\n",
    "    return new_gru_state\n",
    "\n",
    "  def build(self, inputs):\n",
    "    # State last dimension must be n_units.\n",
    "    assert inputs[1].shape[-1] == self._n_units\n",
    "    # The dense layer input is the input and half of the GRU state.\n",
    "    dense_shape = inputs[0].shape[-1] + self._n_units\n",
    "    self.w1 = tf.Variable(tnp.random.uniform(\n",
    "        -0.01, 0.01, (dense_shape, 2 * self._n_units)).astype(tnp.float32))\n",
    "    self.b1 = tf.Variable((tnp.random.randn(2 * self._n_units) * 1e-6 + self._forget_bias\n",
    "               ).astype(tnp.float32))\n",
    "    self.w2 = tf.Variable(tnp.random.uniform(\n",
    "        -0.01, 0.01, (dense_shape, self._n_units)).astype(tnp.float32))\n",
    "    self.b2 = tf.Variable((tnp.random.randn(self._n_units) * 1e-6).astype(tnp.float32))\n",
    "    self._built = True\n",
    "\n",
    "  @property\n",
    "  def weights(self):\n",
    "    return (self.w1, self.b1, self.w2, self.b2)\n",
    "\n",
    "\n",
    "class GRU:\n",
    "\n",
    "  def __init__(self, n_units, forget_bias=0.0, stateful=False):\n",
    "    self._cell = GRUCell(n_units, forget_bias)\n",
    "    self._stateful = stateful\n",
    "    self._built = False\n",
    "\n",
    "  def __call__(self, inputs):\n",
    "    if not self._built:\n",
    "      self.build(inputs)\n",
    "    if self._stateful:\n",
    "      state = self.state.read_value()\n",
    "    else:\n",
    "      state = self._init_state(inputs.shape[0])    \n",
    "    inputs = tnp.transpose(inputs, (1, 0, 2))\n",
    "    output =  tf.scan(\n",
    "        lambda gru_state, x: self._cell((x, gru_state)),\n",
    "        inputs, state)\n",
    "    if self._stateful:\n",
    "      self.state.assign(output[-1, ...])\n",
    "    return tnp.transpose(output, [1, 0, 2])\n",
    "\n",
    "  def _init_state(self, batch_size):\n",
    "    return tnp.zeros([batch_size, self._cell._n_units], tnp.float32)\n",
    "\n",
    "  def reset_state(self):\n",
    "    if not self._stateful:\n",
    "      return\n",
    "    self.state.assign(tf.zeros_like(self.state))\n",
    "\n",
    "  def create_state(self, batch_size):\n",
    "    self.state = tf.Variable(self._init_state(batch_size))\n",
    "\n",
    "  def build(self, inputs):\n",
    "    s = inputs.shape[0:1] + inputs.shape[2:]\n",
    "    shapes = (s, s[:-1] + (self._cell._n_units,))   \n",
    "    self._cell.build([tf.TensorSpec(x, tf.float32) for x in shapes])\n",
    "    if self._stateful:\n",
    "      self.create_state(inputs.shape[0])\n",
    "    else:\n",
    "      self.state = ()\n",
    "    self._built = True\n",
    "    \n",
    "  @property\n",
    "  def weights(self):\n",
    "    return self._cell.weights\n",
    "\n",
    "\n",
    "class Dense:\n",
    "\n",
    "  def __init__(self, n_units, activation=None):\n",
    "    self._n_units = n_units\n",
    "    self._activation = activation\n",
    "    self._built = False\n",
    "\n",
    "  def __call__(self, inputs):\n",
    "    if not self._built:\n",
    "      self.build(inputs)\n",
    "    y = tnp.dot(inputs, self.w) +self.b\n",
    "    if self._activation != None:\n",
    "      y = self._activation(y)\n",
    "    return y\n",
    "\n",
    "  def build(self, inputs):\n",
    "    shape_w = (inputs.shape[-1], self._n_units)\n",
    "    lim = tnp.sqrt(6.0 / (shape_w[0] + shape_w[1]))\n",
    "    self.w = tf.Variable(tnp.random.uniform(-lim, lim, shape_w).astype(tnp.float32))\n",
    "    self.b = tf.Variable((tnp.random.randn(self._n_units) * 1e-6).astype(tnp.float32))\n",
    "    self._built = True\n",
    "\n",
    "  @property\n",
    "  def weights(self):\n",
    "    return (self.w, self.b)\n",
    "\n",
    "\n",
    "class Model:\n",
    "\n",
    "  def __init__(self, vocab_size, embedding_dim, rnn_units, forget_bias=0.0, stateful=False, activation=None):\n",
    "    self._embedding = Embedding(vocab_size, embedding_dim)\n",
    "    self._gru = GRU(rnn_units, forget_bias=forget_bias, stateful=stateful)\n",
    "    self._dense = Dense(vocab_size, activation=activation)\n",
    "    self._layers = [self._embedding, self._gru, self._dense]\n",
    "    self._built = False\n",
    "\n",
    "  def __call__(self, inputs):\n",
    "    if not self._built:\n",
    "      self.build(inputs)\n",
    "    xs = inputs\n",
    "    for layer in self._layers:\n",
    "      xs = layer(xs)\n",
    "    return xs\n",
    "    \n",
    "  def build(self, inputs):\n",
    "    self._embedding.build(inputs)\n",
    "    self._gru.build(tf.TensorSpec(inputs.shape + (self._embedding._embedding_dim,), tf.float32))\n",
    "    self._dense.build(tf.TensorSpec(inputs.shape + (self._gru._cell._n_units,), tf.float32))\n",
    "    self._built = True\n",
    "\n",
    "  @property\n",
    "  def weights(self):\n",
    "    return [layer.weights for layer in self._layers]\n",
    "\n",
    "  @property\n",
    "  def state(self):\n",
    "    return self._gru.state\n",
    "\n",
    "  def create_state(self, *args):\n",
    "    self._gru.create_state(*args)\n",
    "\n",
    "  def reset_state(self, *args):\n",
    "    self._gru.reset_state(*args)\n",
    "\n",
    "\n",
    "model = Model(\n",
    "  vocab_size = vocab_size,\n",
    "  embedding_dim=embedding_dim,\n",
    "  rnn_units=rnn_units,\n",
    "  stateful=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RkA5upJIJ7W7"
   },
   "source": [
    "For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-likelihood of the next character."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-ubPo0_9Prjb"
   },
   "source": [
    "## Try the model\n",
    "\n",
    "Now run the model to see that it behaves as expected.\n",
    "\n",
    "First check the shape of the output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "lzuvs0a4IR6m"
   },
   "outputs": [],
   "source": [
    "  for input_example_batch, target_example_batch in dataset.take(1):\n",
    "    input_example_batch = tnp.asarray(input_example_batch)\n",
    "    example_batch_predictions = model(input_example_batch)\n",
    "    print(example_batch_predictions.shape, \"# (batch_size, sequence_length, vocab_size)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Q6NzLBi4VM4o"
   },
   "source": [
    "In the above example the sequence length of the input is `100` but the model can be run on inputs of any length:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uwv0gEkURfx1"
   },
   "source": [
    "To get actual predictions from the model we need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.\n",
    "\n",
    "Note: It is important to _sample_ from this distribution as taking the _argmax_ of the distribution can easily get the model stuck in a loop.\n",
    "\n",
    "Try it for the first example in the batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "RP56TbSEgcNp"
   },
   "outputs": [],
   "source": [
    "example_batch_predictions[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "4V4MfFg0RQJg"
   },
   "outputs": [],
   "source": [
    "sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)\n",
    "sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QM1Vbxs_URw5"
   },
   "source": [
    "This gives us, at each timestep, a prediction of the next character index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "YqFMUQc_UFgM"
   },
   "outputs": [],
   "source": [
    "sampled_indices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LfLtsP3mUhCG"
   },
   "source": [
    "Decode these to see the text predicted by this untrained model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "xWcFwPwLSo05"
   },
   "outputs": [],
   "source": [
    "print(\"Input: \\n\", repr(\"\".join(idx2char[input_example_batch[0]])))\n",
    "print()\n",
    "print(\"Next Char Predictions: \\n\", repr(\"\".join(idx2char[sampled_indices ])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LJL0Q0YPY6Ee"
   },
   "source": [
    "## Train the model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YCbHQHiaa4Ic"
   },
   "source": [
    "At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "trpqTWyvk0nr"
   },
   "source": [
    "### Loss function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mJRGdSfi-2D8"
   },
   "source": [
    "We define the loss function from scratch, using `tf.nn.log_softmax`. (Our definition is the same as `tf.keras.losses.sparse_categorical_crossentropy`.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "Dhv7DC6TZ-2i"
   },
   "outputs": [],
   "source": [
    "def one_hot(labels, n):\n",
    "  return (labels[..., np.newaxis] == tnp.arange(n)).astype(np.float32)\n",
    "\n",
    "def loss_fn(labels, predictions):\n",
    "  predictions = tf.nn.log_softmax(predictions)\n",
    "  return -tnp.sum(predictions * one_hot(tnp.asarray(labels), predictions.shape[-1]), axis=-1)\n",
    "\n",
    "example_batch_loss  = loss_fn(target_example_batch, example_batch_predictions)\n",
    "print(\"Prediction shape: \", example_batch_predictions.shape, \" # (batch_size, sequence_length, vocab_size)\")\n",
    "print(\"scalar_loss:      \", tnp.mean(example_batch_loss))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mHQWnJCY_fBu"
   },
   "source": [
    "### Optimizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4jHj8s57_NCk"
   },
   "source": [
    "Keeping the DIY spirit, we implement the Adam optimizer from scratch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "NJDx4_SN5Vse"
   },
   "outputs": [],
   "source": [
    "class Adam:\n",
    "\n",
    "  def __init__(self, learning_rate=0.001, b1=0.9, b2=0.999, eps=1e-7):\n",
    "    self._lr = learning_rate\n",
    "    self._b1 = b1\n",
    "    self._b2 = b2\n",
    "    self._eps = eps\n",
    "    self._built = False\n",
    "\n",
    "  def build(self, weights):\n",
    "    self._m = tf.nest.map_structure(lambda x: tf.Variable(tnp.zeros_like(x)), weights)\n",
    "    self._v = tf.nest.map_structure(lambda x: tf.Variable(tnp.zeros_like(x)), weights)\n",
    "    self._step = tf.Variable(tnp.asarray(0, np.int64))\n",
    "    self._built = True\n",
    "\n",
    "  def _update(self, weights_var, grads, m_var, v_var):\n",
    "    b1 = self._b1\n",
    "    b2 = self._b2\n",
    "    eps = self._eps\n",
    "    step = tnp.asarray(self._step, np.float32)\n",
    "    lr = self._lr\n",
    "    weights = tnp.asarray(weights_var)\n",
    "    m = tnp.asarray(m_var)\n",
    "    v = tnp.asarray(v_var)\n",
    "    m = (1 - b1) * grads + b1 * m  # First  moment estimate.\n",
    "    v = (1 - b2) * (grads ** 2) + b2 * v  # Second moment estimate.\n",
    "    mhat = m / (1 - b1 ** (step + 1))  # Bias correction.\n",
    "    vhat = v / (1 - b2 ** (step + 1))   \n",
    "    weights_var.assign_sub((lr * mhat / (tnp.sqrt(vhat) + eps)).astype(weights.dtype))\n",
    "    m_var.assign(m)\n",
    "    v_var.assign(v)\n",
    "\n",
    "  def apply_gradients(self, weights, grads):\n",
    "    if not self._built:\n",
    "      self.build(weights)\n",
    "    tf.nest.map_structure(lambda *args: self._update(*args), weights, grads, self._m, self._v)\n",
    "    self._step.assign_add(1)\n",
    "\n",
    "  @property\n",
    "  def state(self):\n",
    "    return (self._step, self._m, self._v)\n",
    "\n",
    "\n",
    "optimizer = Adam()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3Ky3F_BhgkTW"
   },
   "source": [
    "### Training loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EdhARuXFACy0"
   },
   "source": [
    "Again, we write our training loop from scratch."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IxdOA-rgyGvs"
   },
   "source": [
    "To keep training time reasonable, use 10 epochs to train the model. In Colab, set the runtime to GPU for faster training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "Q4nN6i0oirh2"
   },
   "outputs": [],
   "source": [
    "@tf.function\n",
    "def train_step(inp, target):\n",
    "  with tf.GradientTape() as tape:\n",
    "    # tape.watch(tf.nest.flatten(weights))\n",
    "    predictions = model(inp)\n",
    "    loss = tnp.mean(loss_fn(target, predictions))\n",
    "  weights = model.weights\n",
    "  grads = tape.gradient(loss, weights)\n",
    "  optimizer.apply_gradients(weights, grads)\n",
    "  return loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "RIq1BwUD5mRQ"
   },
   "outputs": [],
   "source": [
    "# Training step\n",
    "EPOCHS = 10\n",
    "\n",
    "model.create_state(BATCH_SIZE)\n",
    "\n",
    "for epoch in range(EPOCHS):\n",
    "  start = time.time()\n",
    "\n",
    "  # initializing the hidden state at the start of every epoch\n",
    "  model.reset_state()\n",
    "\n",
    "  for (batch_n, (inp, target)) in enumerate(dataset):\n",
    "    loss = train_step(inp, target)\n",
    "\n",
    "    if batch_n % 100 == 0:\n",
    "      template = 'Epoch {} Batch {} Loss {}'\n",
    "      print(template.format(epoch+1, batch_n, loss))\n",
    "\n",
    "  print ('Epoch {} Loss {}'.format(epoch+1, loss))\n",
    "  print ('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kKkD5M6eoSiN"
   },
   "source": [
    "## Generate text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DjGz1tDkzf-u"
   },
   "source": [
    "The following code block generates the text:\n",
    "\n",
    "* It Starts by choosing a start string, initializing the RNN state and setting the number of characters to generate.\n",
    "\n",
    "* Get the prediction distribution of the next character using the start string and the RNN state.\n",
    "\n",
    "* Then, use a categorical distribution to calculate the index of the predicted character. Use this predicted character as our next input to the model.\n",
    "\n",
    "* The RNN state returned by the model is fed back into the model so that it now has more context, instead than only one character. After predicting the next character, the modified RNN states are again fed back into the model, which is how it learns as it gets more context from the previously predicted characters.\n",
    "\n",
    "Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LyeYRiuVjodY"
   },
   "source": [
    "To keep this prediction step simple, use a batch size of 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "id": "WvuwZBX5Ogfd"
   },
   "outputs": [],
   "source": [
    "def generate_text(model, start_string):\n",
    "  # Evaluation step (generating text using the learned model)\n",
    "\n",
    "  # Number of characters to generate\n",
    "  num_generate = 1000\n",
    "\n",
    "  # Converting our start string to numbers (vectorizing)\n",
    "  input_eval = [char2idx[s] for s in start_string]\n",
    "  input_eval = tf.expand_dims(input_eval, 0)\n",
    "\n",
    "  # Empty string to store our results\n",
    "  text_generated = []\n",
    "\n",
    "  # Low temperatures results in more predictable text.\n",
    "  # Higher temperatures results in more surprising text.\n",
    "  # Experiment to find the best setting.\n",
    "  temperature = 1.0\n",
    "\n",
    "  # Here batch size == 1\n",
    "  model.create_state(1)\n",
    "  for i in range(num_generate):\n",
    "      predictions = model(input_eval)\n",
    "      # remove the batch dimension\n",
    "      predictions = tf.squeeze(predictions, 0)\n",
    "\n",
    "      # using a categorical distribution to predict the character returned by the model\n",
    "      predictions = predictions / temperature\n",
    "      predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()\n",
    "\n",
    "      # We pass the predicted character as the next input to the model\n",
    "      # along with the previous hidden state\n",
    "      input_eval = tf.expand_dims([predicted_id], 0)\n",
    "\n",
    "      text_generated.append(idx2char[predicted_id])\n",
    "\n",
    "  return (start_string + ''.join(text_generated))\n",
    "\n",
    "print(generate_text(model, start_string=u\"ROMEO: \"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "AM2Uma_-yVIq"
   },
   "source": [
    "The easiest thing you can do to improve the results it to train it for longer (try `EPOCHS=30`).\n",
    "\n",
    "You can also experiment with a different start string, or try adding another RNN layer to improve the model's accuracy, or adjusting the temperature parameter to generate more or less random predictions."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "TensorFlow_NumPy_Text_Generation.ipynb",
   "private_outputs": true,
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
